package com.dxy.data.webcloud.up2u.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxy.data.webcloud.up2u.Service.UserService;
import com.dxy.data.webcloud.up2u.dao.UserMapper;
import com.dxy.data.webcloud.up2u.dao.UserRoleMapper;
import com.dxy.data.webcloud.up2u.domain.UserDO;
import com.dxy.data.webcloud.up2u.domain.UserRoleDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @CLassName: UserServiceImpl
 * @Author: weixin
 * @Description: TODO
 * @DATE: 2018/10/8 下午3:33
 * @Version: 1.0
 */
@Transactional
@Service
public class UserServiceImpl extends ServiceImpl<UserRoleMapper, UserRoleDO> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Override
    public UserDO getByEmail(String email) {
        return userMapper.selectOne(new QueryWrapper<UserDO>().eq("email", email));
    }

    @Override
    public UserDO getByUsername(String username) {
        return userMapper.selectOne(new QueryWrapper<UserDO>().eq("username", username));
    }

    @Override
    public List<UserDO> list(Map<String, Object> map) {
//        return userMapper.list(map);
        return userMapper.selectList(new QueryWrapper<>());
    }

    @Override
    public int save(UserDO user) {
//        int count = userMapper.insertSelective(user);
        int count = userMapper.insert(user);
        Integer userId = user.getId();
        List<Integer> roles = user.getRoleIds();
//        userRoleMapper.removeByUserId(userId);
        userRoleMapper.delete(new QueryWrapper<UserRoleDO>().eq("user_id", userId));
        List<UserRoleDO> list = new ArrayList<>();
        for (Integer roleId : roles) {
            UserRoleDO ur = new UserRoleDO();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        if (list.size() > 0) {
//            userRoleMapper.batchSave(list);
            this.insertBatch(list);
        }
        return count;
    }

}
